<template>
  <view class="purchase-page">
    <!-- 表单内容 -->
    <uni-forms ref="formRef" :modelValue="formData" :rules="rules" label-position="top">

      <!-- 公司选择 -->
      <uni-forms-item label="公司" required name="supplierId">
        <picker
          @change="handleSupplierChange"
          :value="supplierIndex"
          :range="supplierList"
          range-key="name"
        >
          <view class="picker-box">
            <text v-if="formData.supplierId">{{ getSupplierName(formData.supplierId) }}</text>
            <text v-else class="placeholder">请选择公司</text>
            <uni-icons type="bottom" size="14" color="#666"/>
          </view>
        </picker>
      </uni-forms-item>


      <!-- 商品分类 -->
      <uni-forms-item label="商品分类" required name="category">
        <view class="category-input-wrapper">
          <uni-easyinput
            v-model="formData.category"
            placeholder="请输入或选择商品分类"
            @focus="showCategoryDropdown"
            @input="handleCategoryInput"
          />
          <!-- 下拉列表 -->
          <view v-if="showDropdown && filteredCategories.length > 0" class="category-dropdown">
            <view 
              v-for="(item, index) in filteredCategories" 
              :key="index"
              class="category-item"
              @tap="selectCategory(item)"
            >
              {{ item.name }}
            </view>
          </view>
        </view>
      </uni-forms-item>


      <!-- 商品名称 -->
      <uni-forms-item label="商品名称" required name="name">
        <uni-easyinput
          v-model="formData.name"
          placeholder="请输入商品名称"
        />
      </uni-forms-item>

      <!-- 进价 -->
      <uni-forms-item label="单价" required name="purchasePrice">
        <uni-easyinput
          v-model="formData.purchasePrice"
          type="digit"
          placeholder="请输入商品进价"
          @input="calculateTotal"
        />
      </uni-forms-item>

      <!-- 商品数量 -->
      <uni-forms-item label="商品数量" required name="stock">
        <uni-number-box 
          v-model="formData.stock"
          :min="1"
          @change="calculateTotal"
        />
      </uni-forms-item>

      <!-- 总价展示 -->
      <view class="total-price">
        总价：¥{{ totalPrice }}
      </view>
    </uni-forms>

    <!-- 底部按钮 -->
    <view class="footer">
      <button class="submit-btn" @click="handleSubmit">{{ isEdit ? '保存修改' : '确认添加' }}</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { goodsApi } from '@/api/goods'
import { supplierApi } from '@/api/supplier'

const formRef = ref(null)
const isEdit = ref(false)
const goodsId = ref('')
const supplierIndex = ref(0)
const supplierList = ref([])

// 表单数据
const formData = ref({
  name: '',
  purchasePrice: '',
  supplierId: '',
  stock: 1,
  category: ''
})

// 使用计算属性计算总价
const totalPrice = computed(() => {
  const price = Number(formData.value.purchasePrice) || 0
  const quantity = Number(formData.value.stock) || 1
  return (price * quantity).toFixed(2)
})

// 表单校验规则
const rules = {
  name: {
    rules: [{
      required: true,
      errorMessage: '请输入商品名称'
    }]
  },
  purchasePrice: {
    rules: [
      {
        required: true,
        errorMessage: '请输入商品进价'
      },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        errorMessage: '请输入正确的价格格式'
      },
      {
        validateFunction: (rule, value) => {
          const num = Number(value)
          return !isNaN(num) && num > 0
        },
        errorMessage: '进价必须大于0'
      }
    ]
  },
  supplierId: {
    rules: [{
      required: true,
      errorMessage: '请选择公司'
    }]
  },
  stock: {
    rules: [{
      required: true,
      errorMessage: '请设置初始库存'
    }]
  },
  category: {
    rules: [{
      required: true,
      errorMessage: '请输入商品分类'
    }]
  }
}

// 获取商品详情
const getGoodsDetail = async (id) => {
  try {
    const res = await goodsApi.getDetail(id)
    const detail = res
    formData.value = {
      name: detail.name,
      purchasePrice: detail.purchasePrice,
      supplierId: detail.supplierId,
      stock: detail.stock,
      category: detail.category || ''
    }
    
    // 设置公司选中索引
    const index = supplierList.value.findIndex(item => item.id === detail.supplierId)
    if (index > -1) {
      supplierIndex.value = index
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'error'
    })
  }
}

// 获取公司列表
const getSupplierList = async () => {
  try {
    const res = await supplierApi.getList()
    supplierList.value = res.list || []
    
    // 如果是编辑模式，获取商品详情
    if (isEdit.value) {
      await getGoodsDetail(goodsId.value)
    }
  } catch (error) {
    console.error('获取公司列表失败:', error)
  }
}

// 处理公司选择
const handleSupplierChange = async (e) => {
  const index = e.detail.value
  supplierIndex.value = index
  formData.value.supplierId = supplierList.value[index].id
}

// 获取公司名称
const getSupplierName = (id) => {
  const supplier = supplierList.value.find(item => item.id === id)
  return supplier ? supplier.name : ''
}

// 计算总价
const calculateTotal = () => {
  // 由计算属性处理
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()

    if (isEdit.value) {
      // 更新商品
      await goodsApi.update(goodsId.value, formData.value)
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
    } else {
      // 添加商品
      await goodsApi.add(formData.value)
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      })
    }
    formData.value = {
      name: '',
      purchasePrice: '',
      supplierId: formData.value.supplierId,
      stock: 1,
      category: ''
    }
  } catch (error) {
    console.error(isEdit.value ? '更新商品失败:' : '添加商品失败:', error)
    uni.showToast({
      title: isEdit.value ? '更新失败' : '添加失败',
      icon: 'error'
    })
  }
}

// 分类相关数据
const categoryList = ref([])
const showDropdown = ref(false)
const filteredCategories = ref([])

// 获取分类列表
const getCategoryList = async () => {
  try {
    const res = await goodsApi.getCategories()
    categoryList.value = res || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 显示下拉列表
const showCategoryDropdown = () => {
  showDropdown.value = true
  filteredCategories.value = categoryList.value
}

// 处理分类输入
const handleCategoryInput = (value) => {
  if (!value) {
    filteredCategories.value = categoryList.value
  } else {
    filteredCategories.value = categoryList.value.filter(item => 
      item.name.toLowerCase().includes(value.toLowerCase())
    )
  }
  showDropdown.value = true
}

// 选择分类
const selectCategory = (category) => {
  formData.value.category = category.name
  showDropdown.value = false
}

// 点击其他地方关闭下拉列表
const closeDropdown = () => {
  showDropdown.value = false
}

// 页面加载
onShow(async () => {
  // 获取公司列表
  await getSupplierList()
  await getCategoryList() // 添加获取分类列表
})

// 添加点击外部关闭下拉列表的事件监听
onMounted(() => {
  document.addEventListener('click', closeDropdown)
})

onUnmounted(() => {
  document.removeEventListener('click', closeDropdown)
})
</script>

<style>
.purchase-page {
  min-height: 100vh;
  background-color: #F5F5F5;
  padding: 16px;
  padding-bottom: 80px;
}

/* 表单样式 */
.uni-forms {
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
}

:deep(.uni-forms-item) {
  margin-bottom: 24px;
}

:deep(.uni-forms-item__label) {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

:deep(.uni-easyinput__content) {
  background-color: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  height: 40px;
}

/* 选择器样式 */
.picker-box {
  background-color: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  height: 40px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.placeholder {
  color: #999;
}

/* 总价样式 */
.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  text-align: right;
  margin: 16px 0;
}

/* 底部按钮 */
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 16px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.submit-btn {
  width: 100%;
  height: 44px;
  background-color: #1890ff;
  color: #fff;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  border: none;
}

.submit-btn:active {
  background-color: #096dd9;
}

/* 必填项星号样式 */
:deep(.uni-forms-item__required) {
  color: #f56c6c;
}

/* 添加分类输入相关样式 */
.category-input-wrapper {
  position: relative;
  width: 100%;
}

.category-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  max-height: 200px;
  overflow-y: auto;
  background-color: #fff;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.category-item {
  padding: 12px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

.category-item:hover {
  background-color: #F8FAFC;
}

.category-item:active {
  background-color: #E2E8F0;
}
</style> 